const _ = require('lodash');
const async = require('async');
const LoopBackContext = require('loopback-context');
const services = require('../../services');

const eLancoService = services.eLanco;

module.exports = (ctx, modelInstance, cb) => {
  const context = LoopBackContext.getCurrentContext();
  const req = ctx.req;
  const formId = req.body.formId;
  const id = req.params.id;
  const getForm = (next) => {
    eLancoService.getFormIncludeAll(formId, next);
  };
  const getFormDetail = (form, next) => {
    context.set('form', form);
    context.set('flow', form.flow());
    context.set('returnform', ctx.req.body.returnform);
    if (id == 0) return next(null, {});
    eLancoService.getFormDetailIncludeAll(formId, id, next);
  };
  const handleContextEvent = (formDetail, next) => {
    context.set('formDetail', formDetail);
    const form = context.get('form');
    const flow = form.flow();
    const eventName = flow.flowRun.events.submitBefore;
    if (_.isEmpty(eventName)) return next(null);
    eLancoService.handleCustomEvent(form, {}, eventName, next);
  };
  async.waterfall([getForm, getFormDetail, handleContextEvent], cb);
};
